<script setup>
import { ref } from 'vue'
import {
  User,
  Lock,
  OfficeBuilding,
  School,
  Message,
  Medal,
  Postcard,
  Plus,
  Document
} from '@element-plus/icons-vue'
import {
  userUploadAvatarService,
  userRegisterService,
  userGetMdStrService
} from '@/api/user'
import { adminAddExpertService, adminAddPotExpertService } from '@/api/admin'
// 注册相关代码
const imageUrl = ref('')
const mdFile = ref(null)
const FD = new FormData()
const loading = ref(false)
const props = defineProps({
  height: String,
  isPotExpert: Boolean
})
async function handleAvatarChange(file) {
  const img = URL.createObjectURL(file.raw)
  imageUrl.value = img
  registerForm.value.picUrl = file.raw
}

async function handleMdFileChange(file) {
  mdFile.value = file.raw
  registerForm.value.file = file.raw
}

function beforeAvatarUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('上传证件照只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传证件照大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

function beforeMdFileUpload(file) {
  // 常见文本文件扩展名
  const textExts = [
    '.txt',
    '.md',
    '.json',
    '.csv',
    '.log',
    '.xml',
    '.yaml',
    '.yml',
    '.ini',
    '.conf',
    '.py',
    '.js',
    '.ts',
    '.java',
    '.c',
    '.cpp',
    '.h',
    '.css',
    '.scss',
    '.less',
    '.html',
    '.vue'
  ]
  const lowerName = file.name.toLowerCase()
  const isText = textExts.some((ext) => lowerName.endsWith(ext))
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isText) {
    ElMessage.error('只能上传常见文本文件!')
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!')
  }
  return isText && isLt2M
}

// 注册表单
const registerFormRef = ref()
const defaultRegisterForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  gender: '',
  age: 30,
  nationality: '',
  professional: '',
  organization: '',
  academic: '',
  email: '',
  research: '',
  picUrl: '',
  file: '',
  markdownContent: ''
})
const registerForm = ref({
  ...defaultRegisterForm.value
})

// 暴露初始化表单的函数
const initForm = () => {
  // 先清除验证状态，避免选择框的 change 事件触发验证
  if (registerFormRef.value) {
    registerFormRef.value.clearValidate()
    registerFormRef.value.resetFields()
  }
  // 然后重置表单数据
  registerForm.value = { ...defaultRegisterForm.value }
  imageUrl.value = ''
  mdFile.value = null
  // 重置 FormData
  FD.delete('file')
}

// 暴露给父组件使用
defineExpose({
  initForm
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    {
      type: 'number',
      min: 18,
      max: 100,
      message: '年龄需在18-100之间',
      trigger: 'blur'
    }
  ],
  nationality: [{ required: true, message: '请输入民族', trigger: 'blur' }],
  professional: [{ required: true, message: '请选择职称', trigger: 'blur' }],
  organization: [
    { required: true, message: '请输入学院名称', trigger: 'blur' }
  ],
  academic: [{ required: true, message: '请选择最高学历', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  research: [{ required: true, message: '请输入研究方向', trigger: 'blur' }]
}
const isLogin = defineModel('isLogin')
const isAdminLogin = defineModel('isAdminLogin')
const showDrawer = defineModel('showDrawer')

function submitRegisterForm() {
  loading.value = true
  registerFormRef.value.validate((valid) => {
    if (valid) {
      // 生成用户ID
      const userId = new Date().getTime().toString()
      registerForm.value.userId = userId

      // 判断是否需要弹窗
      if (showDrawer.value !== true) {
        // 显示弹窗提示用户ID
        ElMessageBox.alert(
          `您的用户ID是：${userId}\n\n请务必复制并保存此ID，登录时将需要使用此ID。`,
          '注册成功',
          {
            confirmButtonText: '已复制',
            type: 'success',
            dangerouslyUseHTMLString: true,
            customClass: 'user-id-alert',
            beforeClose: (action, instance, done) => {
              if (action === 'confirm') {
                // 复制用户ID到剪贴板
                navigator.clipboard
                  .writeText(userId)
                  .then(() => {
                    ElMessage.success('用户ID已复制到剪贴板')
                  })
                  .catch(() => {
                    ElMessage.warning('复制失败，请手动复制')
                  })
              }
              done()
            }
          }
        ).then(async () => {
          // 这里可以添加注册逻辑
          // 先等待头像上传完成
          FD.append('file', registerForm.value.picUrl)
          const {
            data: { data }
          } = await userUploadAvatarService(FD, 0)
          registerForm.value.picUrl = data
          const { confirmPassword, file, ...baseInfo } = registerForm.value
          // 新增：判断是否选择了文本文件
          if (!mdFile.value) {
            baseInfo.markdownContent = 'unselected'
          }

          await userRegisterService(baseInfo)
          const temId = registerForm.value.userId
          loading.value = false
          ElMessage.success('注册成功！')

          // 注册成功后清零数据并跳转到登录页
          isLogin.value = true
          isAdminLogin.value = false
          showDrawer.value = false
          // 调用userGetMdStrService接口处理MD文件
          if (mdFile.value) {
            const mdFormData = new FormData()
            mdFormData.append('file', mdFile.value)
            await userGetMdStrService(mdFormData, temId, 'EXPERT')
          }
          registerForm.value = { ...defaultRegisterForm.value }
          imageUrl.value = ''
        })
      } else {
        // 不需要弹窗，直接注册
        ;(async () => {
          // 先等待头像上传完成
          FD.append('file', registerForm.value.picUrl)
          if (props.isPotExpert) {
            const {
              data: { data }
            } = await userUploadAvatarService(FD, 1)
            registerForm.value.picUrl = data
          } else {
            const {
              data: { data }
            } = await userUploadAvatarService(FD, 0)
            registerForm.value.picUrl = data
          }
          const { confirmPassword, file, ...baseInfo } = registerForm.value

          if (!mdFile.value) {
            baseInfo.markdownContent = 'unselected'
          }
          if (props.isPotExpert) {
            await adminAddPotExpertService(baseInfo)
          } else {
            await adminAddExpertService(baseInfo)
          }
          const temId = registerForm.value.userId
          loading.value = false
          ElMessage.success('注册成功！')
          if (typeof isLogin !== 'undefined' && isLogin) isLogin.value = true
          if (typeof isAdminLogin !== 'undefined' && isAdminLogin)
            isAdminLogin.value = false
          if (typeof showDrawer !== 'undefined' && showDrawer)
            showDrawer.value = false
          if (mdFile.value) {
            const mdFormData = new FormData()
            mdFormData.append('file', mdFile.value)
            const type = props.isPotExpert ? 'INTERNATIONAL_EXPERT' : 'EXPERT'
            await userGetMdStrService(mdFormData, temId, type)
          }
          // 注册成功后初始化表单
          initForm()
        })()
      }
    } else {
      ElMessage.error('请完善表单信息')
      return false
    }
  })
}
</script>
<template>
  <el-scrollbar :height="height" v-loading="loading">
    <el-form
      :model="registerForm"
      :rules="registerRules"
      ref="registerFormRef"
      label-width="100px"
      class="register-form"
    >
      <el-form-item label="真实姓名" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入真实姓名">
          <template #prefix>
            <el-icon class="icon-color"><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="请输入密码"
          show-password
        >
          <template #prefix>
            <el-icon class="icon-color"><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        label="再次输入密码"
        prop="confirmPassword"
        label-width="auto"
      >
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          show-password
          class="narrow-input"
        >
          <template #prefix>
            <el-icon class="icon-color"><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="registerForm.gender">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number
          v-model="registerForm.age"
          :min="18"
          :max="100"
          placeholder="请输入年龄"
          class="wide-input-number"
        />
      </el-form-item>
      <el-form-item label="民族" prop="nationality">
        <el-input v-model="registerForm.nationality" placeholder="请输入民族" />
      </el-form-item>
      <el-form-item label="职称" prop="professional">
        <el-select v-model="registerForm.professional" placeholder="请选择职称">
          <template #prefix>
            <el-icon class="icon-color"><Medal /></el-icon>
          </template>
          <el-option label="教授" value="教授" />
          <el-option label="副教授" value="副教授" />
          <el-option label="讲师" value="讲师" />
          <el-option label="助教" value="助教" />
          <el-option label="研究生导师" value="研究生导师" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="学院" prop="organization">
        <el-input
          v-model="registerForm.organization"
          placeholder="请输入学院名称"
        >
          <template #prefix>
            <el-icon class="icon-color"><OfficeBuilding /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="最高学历" prop="academic">
        <el-select v-model="registerForm.academic" placeholder="请选择最高学历">
          <template #prefix>
            <el-icon class="icon-color"><School /></el-icon>
          </template>
          <el-option label="博士" value="博士" />
          <el-option label="硕士" value="硕士" />
          <el-option label="学士" value="学士" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" placeholder="请输入邮箱">
          <template #prefix>
            <el-icon class="icon-color"><Message /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="研究方向" prop="research">
        <el-input v-model="registerForm.research" placeholder="请输入研究方向">
          <template #prefix>
            <el-icon class="icon-color"><Postcard /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <div class="upload-container">
        <div class="photo-label">证件照上传</div>
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :before-upload="beforeAvatarUpload"
          :on-change="handleAvatarChange"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">
          请选择您的免冠证件照,格式为JPG或者PNG且大小不能超过2MB
        </div>
      </div>

      <div class="upload-container">
        <div
          style="
            color: #e6a23c;
            font-size: 13px;
            margin-bottom: 4px;
            text-align: center;
          "
        >
          文本文件可传可不传，未上传可登录后补充
        </div>
        <el-upload
          class="md-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :before-upload="beforeMdFileUpload"
          :on-change="handleMdFileChange"
        >
          <el-button type="primary" class="md-upload-btn">
            <el-icon><Document /></el-icon>
            选取文本文件
          </el-button>
        </el-upload>
        <div class="upload-tip">只能上传常见文本文件且大小不超过2MB</div>
        <div v-if="mdFile" class="file-selected-tip">
          已选择文件：{{ mdFile.name }}
        </div>
      </div>

      <el-button type="primary" class="register-btn" @click="submitRegisterForm"
        >注册</el-button
      >
    </el-form>
  </el-scrollbar>
</template>
<style scoped>
.register-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

.icon-color {
  color: #3da890;
}

.narrow-input .el-input__wrapper {
  padding-left: 20px !important;
}

.wide-input-number {
  width: 220px !important;
}

.register-btn {
  width: calc(100% - 80px);
  margin: 0 40px;
  height: 45px;
  background-color: #3da890;
  border: none;
  font-size: 20px;
  letter-spacing: 2px;
  font-size: 16px;
}

.register-btn:hover {
  background-color: #36a07d;
}

.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 40px 0;
}

.upload-tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
  text-align: center;
}

.file-selected-tip {
  color: #3da890;
  font-size: 12px;
  margin-top: 8px;
  text-align: center;
  font-weight: 500;
}

.avatar-uploader .el-upload {
  border: 2px dashed #3da890;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.md-uploader .el-upload {
  display: block;
  text-align: center;
}

.md-upload-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.photo-label {
  text-align: center;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
}

/* 用户ID弹窗样式 */
.user-id-alert .el-message-box__content {
  font-size: 16px;
  line-height: 1.6;
}

.user-id-alert .el-message-box__message {
  white-space: pre-line;
  word-break: break-all;
}
</style>
